import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';

/// author：william on 2021/4/9 15:15
/// email：362661044@qq.com
/// 展开列表按钮
class BaseExpandDownButton extends StatefulWidget {
  final bool isExpanded;
  final double size;
  final double paddingVertical;
  final Color expandedColor;
  final Function(bool) onPressed;

  const BaseExpandDownButton({
    Key key,
    @required this.onPressed,
    this.isExpanded = false,
    this.expandedColor,
    this.size,
    this.paddingVertical,
  }) : super(key: key);
  @override
  _BaseExpandDownButtonState createState() => _BaseExpandDownButtonState();
}

class _BaseExpandDownButtonState extends State<BaseExpandDownButton> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  Animation<double> _iconTurns;

  static final Animatable<double> _iconTurnTween = Tween<double>(begin: 0.0, end: 0.5).chain(CurveTween(curve: Curves.fastOutSlowIn));

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: kThemeAnimationDuration, vsync: this);
    _iconTurns = _controller.drive(_iconTurnTween);
    if (widget.isExpanded == true) {
      _controller.value = math.pi;
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(covariant BaseExpandDownButton oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isExpanded != oldWidget.isExpanded) {
      if (widget.isExpanded) {
        _controller.forward();
      } else {
        _controller.reverse();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: widget.onPressed == null ? null : _handlePressed,
      child: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: widget.paddingVertical ?? 2),
        width: double.infinity,
        child: RotationTransition(
          turns: _iconTurns,
          child: Icon(BaseIconData.x3BottomArrow, size: widget.size ?? 16, color: BaseBodyTheme.iconColor),
        ),
      ),
    );
  }

  void _handlePressed() {
    if (widget.onPressed != null) widget.onPressed(widget.isExpanded);
  }

  // Color get _iconColor {
  //   if (widget.isExpanded && widget.expandedColor != null) return widget.expandedColor;
  //   switch (Theme.of(context).brightness) {
  //     case Brightness.light:
  //       return Colors.black54;
  //     case Brightness.dark:
  //       return Colors.white60;
  //   }
  //   assert(false);
  //   return null;
  // }
}
